﻿using LoveEatRabbit.API.Read.Applications.Commands.Users;
using LoveEatRabbit.API.Read.DTOS;
using LoveEatRabbit.Domain.RBAC;
using LoveEatRabbit.ErrorCode;
using LoveEatRabbit.Infrastructure.Interfaces;
using MediatR;

namespace LoveEatRabbit.API.Read.Applications.CommandHandlers.Users
{
    public class UserQueryCommandHandler : IRequestHandler<UserQueryCommand, APIResult<APIPaging<UserDTO>>>
    {
        private readonly IBaseRespository<UserModel> userRep;
        private readonly IBaseRespository<RoleModel> roleRep;

        public UserQueryCommandHandler(IBaseRespository<UserModel> userRep,
            IBaseRespository<RoleModel> roleRep)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
        }

        public Task<APIResult<APIPaging<UserDTO>>> Handle(UserQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<UserDTO>> result = new APIResult<APIPaging<UserDTO>>();
            result.Code = APIResultCode.查询成功;
            result.Message = APIResultCode.查询成功.ToString();

            var res = from a in userRep.GetAll()
                      join b in roleRep.GetAll() on a.RoleId equals b.RoleId
                      where !a.IsDeleted
                      select new UserDTO
                      {
                          UserId = a.UserId,
                          UserName = a.UserName,
                          UserNickname = a.UserNickname,
                          UserPass = a.UserPass,
                          RoleId = b.RoleId,
                          RoleName = b.RoleName,
                          CreatedTime = a.CreatedTime,
                          States = a.States,
                      };
            //用户名判断
            if (!string.IsNullOrEmpty(request.UserName))
            {
                res = res.Where(x => x.UserName.Contains(request.UserName));
            }

            //总条数
            var totalCount = res.Count();
            //总页数
            var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.Pagsize);
            //排序
            res = res.OrderByDescending(x => x.UserId).Skip((request.Indpage - 1) * request.Pagsize).Take(request.Pagsize);

            APIPaging<UserDTO> paging = new APIPaging<UserDTO>();
            paging.TotalCount=totalCount;
            paging.TotalPage=totalPage;
            paging.Fdata=res.ToList();
            result.Data = paging;

            return Task.FromResult(result);
        }
    }
}
